<?php

namespace app\admin\controller\facrm\contract;

use addons\facrm\library\Helper;
use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 *回款管理
 */
class Receivables extends Backend
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'id,number,remark';
    protected $childrenAdminIds = [];
    protected $noNeedRight = ['product', 'payurl'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('\app\admin\model\facrm\contract\Receivables');

        $this->request->filter(['strip_tags']);
        $config = get_addon_config('facrm');
        $this->view->assign("account_list", $config['account']);
        $this->assignconfig("account_list", $config['account']);
    }

    /**
     * 全部收款
     */
    public function index($scene_list = array())
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $scene_list = $scene_list ? $scene_list : ['all' => '全部收款'];
        if ($this->request->isAjax()) {

            $filter_w = $this->getFilterWhere($scene_list);
            $customer_id = $this->request->param("customer_id");
            if ($customer_id) {
                $filter_w['customer_id'] = $customer_id;
            }
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $this->request->request(['custom' => $filter_w]);
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($filter_w)
                ->order($sort, $order)->fetchSql(false)
                ->count();
            $list = $this->model
                ->where($where)
                ->where($filter_w)
                ->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'customer' => function ($customer) {
                        $customer->field('id,name');
                    },
                    'contract' => function ($customer) {
                        $customer->field('id,name,number');
                    },
                ])
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assignconfig('admin_id', $this->auth->id);
        /**
         * 自定义字段
         */
        $fields = \app\admin\model\facrm\Fields::getCustomFieldsTable('contract_receivables', [], 'isfilter=1 or islist=1');
        if ($fields) {
            $this->assignconfig('fields', json_encode($fields));
        }
        $this->view->assign("scene_list", $scene_list);
        return $this->view->fetch('index');
    }

    /**
     * 我的下属/回款
     */
    public function lists()
    {
        $this->view->assign("action", 'lists');
        return $this->index(['owner' => '我的回款', 'branch' => '下属回款']);
    }

    /**
     * 我的下属/回款[添加]
     * @param null $ids 合同ID
     */
    public function receivablesadd($ids = null)
    {

        $addon_config = get_addon_config('facrm');
        $this->view->assign("account_list", $addon_config['account']);
        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = $flow->where('types', 'receivables')->where('status', 1)->order('id desc')->find();
        if (!$flow_r) $this->error(__('审批配置不存在，请先配置'), url("facrm/flow/index"));

        $contractModel = new \app\admin\model\facrm\Contract();
        $params = $this->request->post("row/a");

        //获取合同情况
        $contract_r = $contractModel->get(isset($params['contract_id']) ? $params['contract_id'] : $ids);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!isset($params['customer_id']))
                $this->error(__('请选择客户'));

            $customer = model('\app\admin\model\facrm\Customer');
            $row_c = $customer->get($params['customer_id']);

            if (!$row_c)
                $this->error(__('没有找到客户'));
            //获取合同情况
            $contractModel = new \app\admin\model\facrm\Contract();
            $contract_r = $contractModel->get($params['contract_id']);
            if (!$contract_r)
                $this->error(__('没有找到合同'));

            //检查是否有权限
            $Auth = new  \addons\facrm\library\Auth();
            if (!$Auth->checkCustomerAuth($row_c, $this->auth)) {
                $this->error(__("您没有权限"));
            }
            $this->add($ids);

        }


        $cprefix = Helper::autoNo($addon_config['rprefix']);
        $this->view->assign("rprefix", $cprefix);//回款前缀
        $this->assignconfig("rprefix", $addon_config['rprefix']);

        $this->view->assign("flow", $flow_r);
        $this->view->assign("contract_r", $contract_r);
        return $this->view->fetch('add', ['addtype' => 'receivablesadd']);

    }

    /**
     * 添加
     * @param null $ids 合同ID
     * @return mixed
     *
     */
    public function add($ids = null)
    {

        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = \app\admin\model\facrm\Flow::getFlow($this->auth->id, 'receivables');

        if (!$flow_r) $this->error(__('审批配置不存在，请先配置'), url("facrm/flow/index"));


        $contractModel = new \app\admin\model\facrm\Contract();
        $planModel = new \app\admin\model\facrm\contract\Plan();
        $params = $this->request->post("row/a");

        //获取合同情况
        $contract_r = $contractModel->get(isset($params['contract_id']) ? $params['contract_id'] : $ids);
        $plan_r=$planModel->where('id',$this->request->request('plan_id','','intval'))->where('contract_id',isset($params['contract_id']) ? $params['contract_id'] : $ids)->find();


        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!isset($params['customer_id']))
                $this->error(__('请选择客户'));

            $customer = model('\app\admin\model\facrm\Customer');
            $row_c = $customer->get($params['customer_id']);

            if (!$row_c)
                $this->error(__('没有找到客户'));

            if (!$contract_r)
                $this->error(__('没有找到合同'));


            $params['return_time'] = $params['return_time'] ? strtotime($params['return_time']) : 0;
            $params = array_merge($params, [
                'create_user_id' => $this->auth->id,
                'owner_user_id' => $this->auth->id,
                'check_status' => 0,
                'order_admin_id' => $contract_r->order_admin_id,
            ]);

            if ($params['pay_type'] == 2) {
                //判断是否支持线上收款
                $payConfig = \addons\facrm\library\Order::getPayConfig();
                if (!$payConfig || $payConfig['values']['online_pay'] != 1) {
                    $this->error(__('线上收款未启用'));
                }
                //如果采用线上收款
                $params['pay_token'] = md5(uniqid('pay_token') . Random::alnum());//生成支付链接凭证
                $params['flow_admin_id'] = '';
            }

            $params = $this->preExcludeFields($params);
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException(true)->validate($validate);

                $result = $this->model->allowField(true)->save($params);
                $receivables_id = $this->model->id;
                hook("facrm_receivables_add", array_merge($params, ['id' => $receivables_id]));
                Db::commit();
            } catch (ValidateException$e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                if ($params['pay_type'] == 2) {
                    //如果采用线上收款就不需要审核

                } else {
                    $flow->addFlow($receivables_id, $this->auth->id, 'receivables', $flow_r);
                }
                $this->success('', '', ['receivables_id' => $receivables_id, 'pay_type' => $params['pay_type']]);
            } else {
                $this->error(__('No rows were inserted'));
            }
        }

        $addon_config = get_addon_config('facrm');
        $cprefix = Helper::autoNo($addon_config['rprefix']);
        $this->view->assign("rprefix", $cprefix);//回款前缀
        $this->assignconfig("rprefix", $addon_config['rprefix']);

        $this->view->assign("flow", $flow_r);
        $this->view->assign("contract_r", $contract_r);
        $this->view->assign("plan_r", $plan_r);
        return $this->view->fetch('add', ['addtype' => 'add']);
    }

    /**
     * 修改
     * @param null $ids
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->check_status == 2) {
            $this->error(__('通过审核的收款不能再更改'));
        }

        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = $flow->where('types', 'receivables')->where('status', 1)->order('id desc')->find();

        $config = get_addon_config('facrm');
        $this->view->assign("account_list", $config['account']);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['return_time'] = $params['return_time'] ? strtotime($params['return_time']) : 0;
                $params['check_status'] = 0;//重新改成待审核状态

                if ($params['pay_type'] == 2) {
                    //判断是否支持线上收款
                    $payConfig = \addons\facrm\library\Order::getPayConfig();
                    if (!$payConfig || $payConfig['values']['online_pay'] != 1) {
                        $this->error(__('线上收款未启用'));
                    }
                    //如果采用线上收款
                    $params['pay_token'] = md5(uniqid('pay_token') . Random::alnum());//生成支付链接凭证
                    $params['flow_admin_id'] = '';
                }


                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $receivables_id = $row->id;
                    if ($params['pay_type'] == 2) {
                        //如果采用线上收款就不需要审核

                    } else {
                        $flow->addFlow($receivables_id, $this->auth->id, 'receivables', $flow_r);
                    }

                    hook("facrm_receivables_edit", array_merge($params, ['id' => $receivables_id]));
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("flow", $flow_r);
        return $this->view->fetch();

    }

    /**
     * 删除
     * @param string $ids
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            $list = $this->model->where($pk, 'in', $ids)->where('owner_user_id', 'in', $this->childrenAdminIds)->select();
            //获取合同情况
            $contractModel = new \app\admin\model\facrm\Contract();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    //扣除回款的金额 return_money
                    $contract_r = $contractModel->withTrashed()->find($v['contract_id']);
                    if ($contract_r && $v['check_status'] == 2) {
                        $contract_r->return_money = $contract_r->return_money - $v['money'];
                        $contract_r->save();
                    }

                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 选择合同
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function selectcontract()
    {
        $scene_list = ['owner' => '我的合同', 'branch' => '下属合同'];
        if ($this->auth->isSuperAdmin() || $this->auth->check('facrm/contract/index/index')) {
            $scene_list['all'] = __("全部合同");
        }
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            return (new \app\admin\controller\facrm\contract\Index())->index($scene_list);
        } else {
            $this->view->assign("scene_list", $scene_list);
        }
        return $this->view->fetch();
    }

    /**
     * 回收站
     * @return string|\think\response\Json
     * @throws Exception
     */
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->onlyTrashed()
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->onlyTrashed()
                ->where($where)
                ->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'customer' => function ($customer) {
                        $customer->field('id,name');
                    },
                    'contract' => function ($customer) {
                        $customer->field('id,name,number');
                    },
                ])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 还原
     */
    public function restore($ids = "")
    {
        $pk = $this->model->getPk();
        if (!$ids) $this->error(__('No rows were updated'));
        $this->model->where($pk, 'in', $ids);
        $list = $this->model
            ->onlyTrashed()
            ->select();
        $contractModel = new \app\admin\model\facrm\Contract();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $k => $v) {
                //扣除回款的金额 return_money
                $contract_r = $contractModel->withTrashed()->where('id', $v['contract_id'])->find();
                if ($contract_r && $v['check_status'] == 2) {
                    $contract_r->return_money = $contract_r->return_money + $v['money'];
                    $contract_r->save();
                }
                // 恢复删除
                $count += $v->save(['delete_time' => null]);
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 详情
     * @param null $ids
     * @return string
     * @throws Exception
     */
    public function detail($ids = null)
    {

        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = $flow->where('types', 'receivables')->where('status', 1)->order('id desc')->find();

        $config = get_addon_config('facrm');
        $this->view->assign("account_list", $config['account']);
        $this->view->assign("row", $row);
        $this->view->assign("flow", $flow_r);
        return $this->view->fetch('detail', ['action' => 'detail']);

    }

    /**
     * 处理过滤where条件
     * @return array
     */
    private function getFilterWhere($scene_list)
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        $filter['scene_id'] = isset($filter['scene_id']) ? $filter['scene_id'] : 1;
        if (isset($filter['scene_id'])) {

            if (!isset($scene_list[$filter['scene_id']])) {
                $this->error(__("您没有权限"));
            }
            switch ($filter['scene_id']) {
                case 'all':
                    //全部
                    break;
                case 'owner':
                    //我的
                    $filter_w['order_admin_id'] = $this->auth->id;
                    break;
                case 'branch':
                    //下级
                    $this->childrenAdminIds = $this->auth->getChildrenAdminIds(false);
                    $filter_w['order_admin_id'] = ['in', $this->childrenAdminIds];
                    break;
                default://其它的还做TODO
                    $filter_w['order_admin_id'] = $this->auth->id;
            }
            unset($filter['scene_id']);
            $this->request->get(['filter' => json_encode($filter)]);
        }
        return $filter_w;
    }


    /**
     * 生成支付链接
     * @param null $ids
     * @return string
     * @throws Exception
     */
    public function payurl($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row->pay_type != 2) {
            $this->error(__('不是线上收款单' . $row->pay_type));
        }
        $check_data = \addons\facrm\library\Order::checkPay($row, 'pay', $pay_config);
        if ($check_data['code'] != 1) {
            $this->error(__($check_data['msg']));
        }
        //如果已经支付了就是续费链接
        if ($row->pay_status == 1) {
            $this->error(__('已经支付'));
        } else {
            //10天就重新刷新支付凭证
            if (!$row->pay_token || (time() - $row->update_time) > 864000) {
                $row->pay_token = md5($row->id . uniqid() . Random::uuid());
                $row->save();
            }
            $url = addon_url('facrm/order/pay', ['pay_token' => $row->pay_token], '', true);
            $this->view->assign("url", $url);
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();

    }


}
